package com.sino.tb.attachment;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
import xpubbean.Db.Conn;
import xpubbean.Db.ResultSetPlus;

public class FileViewServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public FileViewServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        getFile(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
        getFile(request, response);
    }

    private String getMimeType(String fileUrl) throws java.io.IOException,
            MalformedURLException {
        String type = null;
        URL u = new URL(fileUrl);
        URLConnection uc = null;
        uc = u.openConnection();
        type = uc.getContentType();
        return type;
    }

    private void getFile(HttpServletRequest request, HttpServletResponse response) {
        String strAccDetSeq=request.getParameter("c_seq");
        String	sql="select INFO.C_FILE_NAME,                     "+
        "       STORAGE.C_FTP_PATH,                       "+
        "       STORAGE.C_STORAGE_IP,                     "+
        "       STORAGE.C_FTP_USER,                       "+
        "       STORAGE.C_FTP_PWD                         "+
        "  from T_ATTACHMENT_INFO INFO,                   "+
        "       T_STORAGE_LOC     LOC,                    "+
        "       T_STORAGE_ORG     ORG,                    "+
        "       T_ST_STORAGE      STORAGE                 "+
        " where INFO.C_ATTACHMENT_ID = "+strAccDetSeq+
        "   AND LOC.C_ATTACHMENT_ID = INFO.C_ATTACHMENT_ID"+
        "   AND LOC.C_ID = ORG.C_ID                       "+
        "   AND ORG.C_STORAGE_ID = STORAGE.c_Storage_Id   ";
        Conn lo_conn = new Conn();
        Connection conn =lo_conn.getConnection();
        System.out.println("FILE UPLOAD getConnection");
        ResultSetPlus class_rs = null;
        class_rs=new ResultSetPlus(sql, conn);

        class_rs.next();
        String c_ip=class_rs.getFieldStr("C_STORAGE_IP");
        String c_path=class_rs.getFieldStr("C_FTP_PATH")+"/"+class_rs.getFieldStr("C_FILE_NAME");
        String c_user = class_rs.getFieldStr("C_FTP_USER");
        String c_pwd = class_rs.getFieldStr("C_FTP_PWD");
        try {
            ServletOutputStream out = response.getOutputStream();



            FtpClient ftpClient=new FtpClient();
            ftpClient.openServer(c_ip);
            ftpClient.login(c_user, c_pwd);
            if (c_path.length()!=0) ftpClient.cd(class_rs.getFieldStr("C_FTP_PATH"));
            ftpClient.binary();
            TelnetInputStream is=ftpClient.get(class_rs.getFieldStr("C_FILE_NAME"));

            String mime  = new MimetypesFileTypeMap().getContentType(new File(class_rs.getFieldStr("C_FILE_NAME")));
            response.setContentType(mime+"; charset=GBK;");
            response.setHeader("Content-Disposition","filename="+class_rs.getFieldStr("C_FILE_NAME"));

            byte[] bytes=new byte[1024];
            int c;
            while ((c=is.read(bytes))!=-1) {
                out.write(bytes,0,c);
            }
            is.close();
            out.close();
            ftpClient.closeServer();
            response.sendRedirect("/attachment/FileUpdateView.jsp");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            lo_conn.closeConnection(conn);
        }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
